package mwa.cs.sm.ctrl;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import javazoom.upload.MultipartFormDataRequest;
import javazoom.upload.UploadBean;
import javazoom.upload.UploadException;
import javazoom.upload.UploadFile;
import mwa.cs.dao.GenDocDAO;
import mwa.cs.dao.PressReleaseDAO;
import mwa.cs.dao.SMErrorLogDAO;
import mwa.cs.database.Database;
import mwa.cs.model.PressRelese;
import mwa.cs.util.JDate;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
/**
 * Servlet implementation class CS11013Srvl
 */
public class CS11013Srvl extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private Database db ;
	public String vaNewImage ;
	public String vaDetailShow;
	public String vaTopicShow;
	public String vaTopicEdit;
	public String vaTopicDelete;
	private String vaAgentBrowser;
	private String vaUrlAddress;
	private int vnSiteId;
	private int vnUserId;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CS11013Srvl() {
        super();
    }
    
    public void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
    	String vaProcessType = request.getParameter("process_type");
    	vaUrlAddress = request.getParameter("url_address");
    	vaAgentBrowser = request.getParameter("agent_browser");
		vnSiteId = Integer.parseInt(request.getSession().getAttribute("site_id").toString());
		vnUserId = Integer.parseInt(request.getSession().getAttribute("user_id").toString());
		if(vaProcessType.equals("insert")){ 
			insert(request,response);	
		}else if (vaProcessType.equals("insert_upload")){
			insert_upload(request,response);	
		}else if(vaProcessType.equals("edit")){ 
			edit(request , response);
		}else if(vaProcessType.equals("delete")){
			delete(request,response);
		}else if(vaProcessType.equals("update")) {
			update(request,response);
		}else if (vaProcessType.equals("getDataTable")){
			getDataTable(request,response);
		}else if(vaProcessType.equals("update&upload")) {
			update_upload(request,response);
		}
    }
    
    public void edit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/JSON");
		this.db = new Database();	
		String vaToPic = request.getParameter("topic");
		String vaStartData = JDate.saveDate(request.getParameter("start_date"));
		String vaEndDate = JDate.saveDate(request.getParameter("end_date"));
		String[] vaTopicArray = vaToPic.split("(\\...)");
	        for(int d=0; d<vaTopicArray.length; d++){
	        	vaTopicEdit= vaTopicArray[0];
	        }
	    JSONObject voJsonObject = new JSONObject();
    	PressReleaseDAO voReleaseDAO =new PressReleaseDAO(db);
    	Map<String, Object>  voMap = voReleaseDAO.findPressReleseByTopic(vnSiteId, vaTopicEdit, vaStartData, vaEndDate);
    	voJsonObject.put("topic",voMap.get("TOPIC").toString());
    	voJsonObject.put("detail",voMap.get("DETAIL").toString());
    	voJsonObject.put("url",voMap.get("IMAGE_URL").toString());
    	response.getWriter().print(voJsonObject.toJSONString());
    	this.db.close();
    	
    }

    public void update(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8"); 
		response.setContentType("text/JSON");
		this.db = new Database();
		
		String vaPin = request.getParameter("pin");
		String vaToPic = request.getParameter("topic");
		String vaDetail = request.getParameter("detail");
		String vaStartData = JDate.saveDate(request.getParameter("start_date"));
		String vaEndDate = JDate.saveDate(request.getParameter("end_date"));
		String vaOldTopic =request.getParameter("oldTopic");
		String vaOldNameImage = request.getParameter("oldNameImage");
		String vaOldStatDate = JDate.saveDate(request.getParameter("oldStartDate"));
		String vaOldEndDate =  JDate.saveDate(request.getParameter("oldEndDate"));
		//run tomcat
		/*String vapin = new String(request.getParameter("pin").getBytes("ISO8859_1"), "UTF-8");
		String vatoPic = new String(request.getParameter("topic").getBytes("ISO8859_1"), "UTF-8");
		String vadetail = new String(request.getParameter("detail").getBytes("ISO8859_1"), "UTF-8");
		String vastartData = new String(JDate.saveDate(request.getParameter("start_date")).getBytes("ISO8859_1"), "UTF-8");
		String vaendDate = new String(JDate.saveDate(request.getParameter("end_date")).getBytes("ISO8859_1"), "UTF-8");
		String vaoldTopic =new String (request.getParameter("oldTopic").getBytes("ISO8859_1"), "UTF-8");
		*/
		
		
		try{
			db.beginTransaction();	
			
			PressRelese poPressRelese = new PressRelese();
			poPressRelese.setVnSiteId(vnSiteId);
			poPressRelese.setVaPin(vaPin);
			poPressRelese.setVaTopic(vaToPic);
			poPressRelese.setVaDetail(vaDetail);
			poPressRelese.setVaStartDate(vaStartData);
			poPressRelese.setVaEndDate(vaEndDate);
			poPressRelese.setVaImageUrl(vaOldNameImage);
			poPressRelese.setVaType("S");
			poPressRelese.setVnUpdateUserId(vnUserId);
			poPressRelese.setVaUpdateDate(JDate.getDate());
			poPressRelese.setVaUpdateTime(JDate.getTime());
			
			PressReleaseDAO daoReleaseDAO = new PressReleaseDAO(db);
			daoReleaseDAO.updatePressRelease(vnSiteId, vaOldTopic, vaOldStatDate, vaOldEndDate, poPressRelese);
			response.getWriter().write("update success");
			
			db.commit();
		} catch (Exception e) {
			SMErrorLogDAO.getInstance().addLog(0, "CS11013", JDate.getDate(), JDate.getTime(),vnUserId, "CS11013Srvl", e.getMessage(),vaUrlAddress, vaAgentBrowser);
			db.rollback();
		}finally{
			db.close();
		}
    }
    
    
    public void update_upload(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8"); 
		response.setContentType("text/JSON");
		this.db = new Database();
		String vaPin = request.getParameter("pin");
		String vaToPic = request.getParameter("topic");
		String vaDetail = request.getParameter("detail");
		String vaStartData = JDate.saveDate(request.getParameter("start_date"));
		String vaEndDate = JDate.saveDate(request.getParameter("end_date"));
		String vaOldTopic = request.getParameter("oldTopic");
		
		//run tomcat
		/*String vapin = new String(request.getParameter("pin").getBytes("ISO8859_1"), "UTF-8");
		String vatoPic = new String(request.getParameter("topic").getBytes("ISO8859_1"), "UTF-8");
		String vadetail = new String(request.getParameter("detail").getBytes("ISO8859_1"), "UTF-8");
		String vastartData = new String(JDate.saveDate(request.getParameter("start_date")).getBytes("ISO8859_1"), "UTF-8");
		String vaendDate = new String(JDate.saveDate(request.getParameter("end_date")).getBytes("ISO8859_1"), "UTF-8");
		String vaoldTopic = new String(request.getParameter("oldTopic").getBytes("ISO8859_1"), "UTF-8");*/
		try{
			db.beginTransaction();	
			PressRelese voPressRelese = new PressRelese();
			voPressRelese.setVnSiteId(vnSiteId);
			voPressRelese.setVaPin(vaPin);
			voPressRelese.setVaTopic(vaToPic);
			voPressRelese.setVaDetail(vaDetail);
			voPressRelese.setVaStartDate(vaStartData);
			voPressRelese.setVaEndDate(vaEndDate);
			voPressRelese.setVaImageUrl(vaNewImage);
			voPressRelese.setVaType("S");
			voPressRelese.setVnUpdateUserId(vnUserId);
			voPressRelese.setVaUpdateDate(JDate.getDate());
			voPressRelese.setVaUpdateTime(JDate.getTime());
			
			PressReleaseDAO voReleaseDAO = new PressReleaseDAO(db);
			voReleaseDAO.updatePressRelease(vnSiteId, vaOldTopic, vaStartData, vaEndDate, voPressRelese);
			response.getWriter().write("update success");
			
			db.commit();
		} catch (Exception e) {
			SMErrorLogDAO.getInstance().addLog(0, "CS11013", JDate.getDate(), JDate.getTime(),vnUserId, "CS11013Srvl", e.getMessage(),vaUrlAddress, vaAgentBrowser);
			db.rollback();
		}finally{
			db.close();
		}		
    }
    
 
    public void insert_upload(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8"); 
		response.setContentType("text/JSON");
		this.db = new Database();
		String vaPin = request.getParameter("pin");
		String vaToPic = request.getParameter("topic");
		String vaDetail = request.getParameter("detail");
		String vaStartData = JDate.saveDate(request.getParameter("start_date"));
		String vaEndDate = JDate.saveDate(request.getParameter("end_date"));
		
		//run tomcat
		/*String vapin = new String(request.getParameter("pin").getBytes("ISO8859_1"), "UTF-8");
		String vatoPic = new String(request.getParameter("topic").getBytes("ISO8859_1"), "UTF-8");
		String vadetail = new String(request.getParameter("detail").getBytes("ISO8859_1"), "UTF-8");
		String vastartData = new String(JDate.saveDate(request.getParameter("start_date")).getBytes("ISO8859_1"), "UTF-8");
		String vaendDate = new String(JDate.saveDate(request.getParameter("end_date")).getBytes("ISO8859_1"), "UTF-8");
		*/
		
		try{
			db.beginTransaction();	
			
			PressRelese poPressRelese = new PressRelese();
			poPressRelese.setVnSiteId(vnSiteId);
			poPressRelese.setVaPin(vaPin);
			poPressRelese.setVaTopic(vaToPic);
			poPressRelese.setVaDetail(vaDetail);
			poPressRelese.setVaStartDate(vaStartData);
			poPressRelese.setVaEndDate(vaEndDate);
			poPressRelese.setVaImageUrl(vaNewImage);
			poPressRelese.setVaType("S");
			poPressRelese.setVnInsertUserId(vnUserId);
			poPressRelese.setVaInsertDate(JDate.getDate());
			poPressRelese.setVaInsertTime(JDate.getTime());
			
			PressReleaseDAO voReleaseDAO = new PressReleaseDAO(db);
			voReleaseDAO.addPressRelese(poPressRelese);
			response.getWriter().write("success insert_upload");
			
			db.commit();
		} catch (Exception e) {
			SMErrorLogDAO.getInstance().addLog(0, "CS11013", JDate.getDate(), JDate.getTime(),vnUserId, "CS11013Srvl", e.getMessage(),vaUrlAddress, vaAgentBrowser);
			db.rollback();
		}finally{
			db.close();
		}	
    }
    
    public void insert(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8"); 
		response.setContentType("text/JSON");
		this.db = new Database();
		String vaPin = request.getParameter("pin");
		String vaToPic = request.getParameter("topic");
		String vaDetail = request.getParameter("detail");
		String vaStartData = JDate.saveDate(request.getParameter("start_date"));
		String vaEndDate = JDate.saveDate(request.getParameter("end_date"));
		//run tomcat
		/*String vapin = new String(request.getParameter("pin").getBytes("ISO8859_1"), "UTF-8");
		String vatoPic = new String(request.getParameter("topic").getBytes("ISO8859_1"), "UTF-8");
		String vadetail = new String(request.getParameter("detail").getBytes("ISO8859_1"), "UTF-8");
		String vastartData = new String(JDate.saveDate(request.getParameter("start_date")).getBytes("ISO8859_1"), "UTF-8");
		String vaendDate = new String(JDate.saveDate(request.getParameter("end_date")).getBytes("ISO8859_1"), "UTF-8");*/
	
		String image_default ="news-thumb.jpg";
		try{
			db.beginTransaction();	
			
			PressRelese poPressRelese = new PressRelese();
			poPressRelese.setVnSiteId(vnSiteId);
			poPressRelese.setVaPin(vaPin);
			poPressRelese.setVaTopic(vaToPic);
			poPressRelese.setVaDetail(vaDetail);
			poPressRelese.setVaStartDate(vaStartData);
			poPressRelese.setVaEndDate(vaEndDate);
			poPressRelese.setVaImageUrl(image_default);
			poPressRelese.setVaType("S");
			poPressRelese.setVnInsertUserId(vnUserId);
			poPressRelese.setVaInsertDate(JDate.getDate());
			poPressRelese.setVaInsertTime(JDate.getTime());
			
			PressReleaseDAO voReleaseDAO = new PressReleaseDAO(db);
			voReleaseDAO.addPressRelese(poPressRelese);
			response.getWriter().write("success insert");
			
			db.commit();
		} catch (Exception e) {
			SMErrorLogDAO.getInstance().addLog(0, "CS11013", JDate.getDate(), JDate.getTime(),vnUserId, "CS11013Srvl", e.getMessage(),vaUrlAddress, vaAgentBrowser);
			db.rollback();
		}finally{
			db.close();
		}
    }
    
    public void delete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8"); 
		response.setContentType("text/JSON");
		this.db = new Database();
		String vaToPic = request.getParameter("topic");
		String vaStartData = JDate.saveDate(request.getParameter("startDate"));
		String vaEndDate = JDate.saveDate(request.getParameter("endDate"));
		String vaNameImage = request.getParameter("url");
		
		//run tomcat
		/*String vatoPic = new String(request.getParameter("topic").getBytes("ISO8859_1"), "UTF-8");
		String vastartData = JDate.saveDate(request.getParameter("startDate"));
		String vaendDate = JDate.saveDate(request.getParameter("endDate"));
		String vanameImage = new String(request.getParameter("url").getBytes("ISO8859_1"),"UTF-8");*/
		
        
        try{
        	db.beginTransaction();
        	
        	String[] vaTopicArray = vaToPic.split("(\\...)");
            for(int d=0; d<vaTopicArray.length; d++){
            	vaTopicDelete= vaTopicArray[0];
            }
        	PressReleaseDAO voReleaseDAO =  new PressReleaseDAO(db);
    		voReleaseDAO.deletePressReleseBySitId(vnSiteId,vaTopicDelete,vaStartData,vaEndDate);
    		if(!vaNameImage.equals("news-thumb.jpg")){
    			File voDeleteFile = new File(request.getRealPath("/")+"assets/images/new/"+vaNameImage);
    			voDeleteFile.delete();
    			response.getWriter().write("Success Delete");
    		}
        	
        	db.commit();
        } catch (Exception e) {
        	SMErrorLogDAO.getInstance().addLog(0, "CS11013", JDate.getDate(), JDate.getTime(),vnUserId, "CS11013Srvl", e.getMessage(),vaUrlAddress, vaAgentBrowser);
        	db.rollback();
        }finally{
        	db.close();
        }
    }
    
    
	public void getDataTable(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8"); 
		response.setContentType("text/JSON");
		JSONObject voObject = new JSONObject();
		JSONArray voRow = new JSONArray();
		JSONArray voColumn = null;
		PrintWriter voOut = response.getWriter();
		this.db = new Database();
		PressReleaseDAO voReleaseDAO = new PressReleaseDAO(db);
		List<Map<String , Object>> voListRelease;
		voListRelease = voReleaseDAO.findPressReleaseBySiteId(vnSiteId);
		 String[] vaDetails = null; String[] vaTopics = null;
		for(int i=0 ;i<voListRelease.size();i++){
			Map<String , Object> voMapItem = (Map<String , Object>) voListRelease.get(i);
			voColumn = new JSONArray();
			voColumn.add(i+1);
			voColumn.add(voMapItem.get("PIN").toString());
			voColumn.add(voMapItem.get("IMAGE_URL").toString());
			//split for show 
			vaTopics = ((String) voMapItem.get("TOPIC")).split("(?<=\\G.{20})");
			for(int d=0; d<vaTopics.length; d++){
		            vaTopicShow = vaTopics[0]+"...";
		       }
	        vaDetails = ((String) voMapItem.get("DETAIL")).split("(?<=\\G.{40})");
	        for(int d=0; d<vaDetails.length; d++){
	            vaDetailShow = vaDetails[0]+"...";
	        }
	        voColumn.add(vaTopicShow);
			voColumn.add(vaDetailShow);
			voColumn.add(JDate.showDate(voMapItem.get("START_DATE").toString()));
			voColumn.add(JDate.showDate(voMapItem.get("END_DATE").toString()));
			voRow.add(voColumn);
			
		}
		voObject.put("aaData", voRow);
		voOut.print(voObject.toJSONString());
		this.db.close();
	}
	
	
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request,response);
		
	}
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String vaProcessType = request.getParameter("process_type");
		
		if(vaProcessType != null && !vaProcessType.equals("")){ 
			processRequest(request,response);
		}else{
			MultipartFormDataRequest voMultipartForm = null;
	    	 UploadBean voUpload = new UploadBean();
	    			try {
						voMultipartForm = new MultipartFormDataRequest(request);
						voUpload.setFolderstore(request.getRealPath("/")+"assets/images/new");
						voUpload.setWhitelist("*.jpg,*.png,*.gif");
						voUpload.setOverwrite(true);
						voUpload.store(voMultipartForm,"fileImage");
		    			
		    			Hashtable voFileHashtable = voMultipartForm.getFiles();
		    			UploadFile voUploadFile = (UploadFile) voFileHashtable.get("fileImage");
		    			String nameImage = voUploadFile.getFileName();
		    			
		    			File voTobeRenameFile = new File(request.getRealPath("/")+"assets/images/new/"+nameImage);
		    			 this.db = new Database();
			    		 GenDocDAO daoGenDocDAO = new GenDocDAO(db);
			    		 vaNewImage = "NEWS"+daoGenDocDAO.generatingNextMNDoc()+".jpg";
		    			 voTobeRenameFile.renameTo(new File(request.getRealPath("/")+"assets/images/new/"+vaNewImage));
		    			
					} catch (UploadException e) {
						e.printStackTrace();
					}
	    			this.db.close();
	    			
			}
		}

}
